package com.maimao.search.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.maimao.core.model.resp.PageResult;
import com.maimao.core.utils.MapUtils;
import com.maimao.model.goods.log.GoodsCheck;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.IndicesClient;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.InternalAggregations;
import org.elasticsearch.search.aggregations.InternalMultiBucketAggregation;
import org.elasticsearch.search.aggregations.bucket.terms.LongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import sun.jvm.hotspot.debugger.Page;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author MaoLin Wang
 * @date 2020/12/27 12:41 下午
 */
@Service
public class EsUtil {
    private Logger logger = LoggerFactory.getLogger(EsUtil.class);


    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Value("${maimao.es.goods.type}")
    private String type;
    private static final String DEFAULT_SHARDS = "1";
    private static final String DEFAULT_REPLICAS = "1";

    public SearchResponse search(SearchRequest searchRequest) {

        return search(searchRequest, null);
    }

    /**
     * 搜搜 返回总记录数
     *
     * @param jsonArray 搜索结果保存的位置
     */
    public SearchResponse search(SearchRequest searchRequest, JSONArray jsonArray) {
        SearchResponse searchResponse = null;
        try {
            searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            if (jsonArray == null) {
                return searchResponse;
            }
            SearchHits hits = searchResponse.getHits();
            SearchHit[] searchHits = hits.getHits();
            if (searchHits.length > 0) {
                Arrays.stream(searchHits).forEach(hit -> jsonArray.add(JSON.parseObject(hit.getSourceAsString())));
            }
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("搜索出错，searchRequest:{},error=>{}", searchRequest, e.getMessage());
        }
        return searchResponse;
    }

    /**
     * 根据搜索结果获取聚合桶 返回Long类型的聚合统
     *
     * @return Map<String, List < LongTerms.Bucket>>  key:聚合名 value：对应的桶
     */
    public Map<String, List<ParsedLongTerms.ParsedBucket>> getAggLongBuckets(SearchResponse searchResponse) {
        Aggregations aggregations = searchResponse.getAggregations();
        Map<String, Aggregation> aggsMap = aggregations.getAsMap();
        Map<String, List<ParsedLongTerms.ParsedBucket>> res = new HashMap<>(MapUtils.initCapacity(aggsMap.size()));
        for (Map.Entry<String, Aggregation> aggregationEntry : aggsMap.entrySet()) {
            ParsedLongTerms parsedLongTerms = (ParsedLongTerms) aggregationEntry.getValue();
            List<ParsedLongTerms.ParsedBucket> buckets = (List<ParsedLongTerms.ParsedBucket>) parsedLongTerms.getBuckets();
            res.put(aggregationEntry.getKey(), buckets);
        }
        return res;
    }

    /**
     * 根据搜索结果获取聚合桶 返回String类型的聚合统
     *
     * @return Map<String, List < LongTerms.Bucket>>  key:聚合名 value：对应的桶
     */
    public Map<String, List<ParsedStringTerms.ParsedBucket>> getAggStringBuckets(SearchResponse searchResponse) {
        Aggregations aggregations = searchResponse.getAggregations();
        Map<String, Aggregation> aggsMap = aggregations.getAsMap();
        Map<String, List<ParsedStringTerms.ParsedBucket>> res = new HashMap<>(MapUtils.initCapacity(aggsMap.size()));
        for (Map.Entry<String, Aggregation> aggregationEntry : aggsMap.entrySet()) {
            ParsedStringTerms parsedStringTerms = (ParsedStringTerms) aggregationEntry.getValue();
            List<ParsedStringTerms.ParsedBucket> buckets = (List<ParsedStringTerms.ParsedBucket>) parsedStringTerms.getBuckets();
            res.put(aggregationEntry.getKey(), buckets);
        }
        return res;
    }

    private List<LongTerms.Bucket> getLongTermsBucket(InternalMultiBucketAggregation aggregations) {
        return aggregations.getBuckets();
    }


    public boolean createIndex(String index, XContentBuilder builder) throws IOException {
        if (StringUtils.isEmpty(index)) {
            return false;
        }
        CreateIndexRequest createIndexRequest = createDefaultIndexRequest(index);
        createIndexRequest.mapping("doc", builder);
        return createIndex(createIndexRequest);
    }

    public boolean createIndex(String index, String source) throws IOException {
        if (StringUtils.isEmpty(index)) {
            return false;
        }
        CreateIndexRequest createIndexRequest = createDefaultIndexRequest(index);
        createIndexRequest.mapping(type, source, XContentType.JSON);
        return createIndex(createIndexRequest);
    }


    private CreateIndexRequest createDefaultIndexRequest(String index) {
        CreateIndexRequest createIndexRequest = new CreateIndexRequest(index);
        createIndexRequest.settings(Settings.builder().put("number_of_shards", DEFAULT_SHARDS).put("number_of_replicas", DEFAULT_REPLICAS));
        return createIndexRequest;
    }

    private boolean createIndex(CreateIndexRequest request) throws IOException {
        IndicesClient indices = restHighLevelClient.indices();
        CreateIndexResponse createIndexResponse = indices.create(request, RequestOptions.DEFAULT);
        return createIndexResponse.isAcknowledged();
    }

    public <T> PageResult<T> getPageResult(JSONArray jsonArray, Class<T> clazz, SearchResponse response) {
        return new PageResult<>(jsonArray.toJavaList(clazz), response.getHits().totalHits);
    }
}
